package com.ccl.iot.dvr.utils;

import android.content.Context;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SimpleTarget;
import com.ccl.iot.publics.ThreadPoolUtils;

import java.io.File;

/**
 * @description：
 * @author： HD
 * @time：2017/7/28
 */

public class GlideUtil {

    public static final int SCALE_CENTER_CROP = 0;
    public static final int SCALE_FIT_CENTER = 1;

    /**
     * Glide特点
     * 使用简单
     * 可配置度高，自适应程度高
     * 支持常见图片格式 Jpg png gif webp
     * 支持多种数据源  网络、本地、资源、Assets 等
     * 高效缓存策略    支持Memory和Disk图片缓存 默认Bitmap格式采用RGB_565内存使用至少减少一半
     * 生命周期集成   根据Activity/Fragment生命周期自动管理请求
     * 高效处理Bitmap  使用Bitmap Pool使Bitmap复用，主动调用recycle回收需要回收的Bitmap，减小系统回收压力
     * 这里默认支持Context，Glide支持Context,Activity,Fragment，FragmentActivity
     */

    //默认加载
    public static void loadImageView(Context context, Object path, ImageView imageView) {
      Glide.with(context.getApplicationContext()).load(path).diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
    }


    public static void loadImageViewNoCacheDisk(Context context, Object path, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).dontAnimate().into(imageView);
    }


    public static void clear(ImageView imageView){
        Glide.clear(imageView);
    }

    public static void loadImageView(Context context, Object path, ImageView imageView,int scaleType) {

        switch (scaleType){
            case SCALE_CENTER_CROP:
                Glide.with(context.getApplicationContext()).load(path).centerCrop().into(imageView);
                break;
            case SCALE_FIT_CENTER:
                Glide.with(context.getApplicationContext()).load(path).fitCenter().into(imageView);
                break;
            default:
                break;
        }

    }

    //加载指定大小
    public static void loadImageViewSize(Context context, Object path, int width, int height, ImageView imageView) {
        Glide.with(context).load(path).diskCacheStrategy(DiskCacheStrategy.NONE).override(width, height).into(imageView);
    }

    public static void loadImageViewSize(Fragment fragment, Object path, int width, int height, ImageView imageView) {
        Glide.with(fragment).load(path).diskCacheStrategy(DiskCacheStrategy.NONE).override(width, height).into(imageView);
    }

    public static void loadImageViewSizeNoCacheDisk(Context context, Object path, int width, int height, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).diskCacheStrategy(DiskCacheStrategy.NONE).override(width, height).into(imageView);
    }

    public static void loadImageViewSize(Context context, Object path, int width, int height, ImageView imageView,int scaleType) {

        switch (scaleType){
            case SCALE_CENTER_CROP:
                Glide.with(context.getApplicationContext()).load(path).override(width, height).centerCrop().into(imageView);
                break;
            case SCALE_FIT_CENTER:
                Glide.with(context.getApplicationContext()).load(path).override(width, height).fitCenter().into(imageView);
                break;
            default:
                break;
        }
    }

    //设置加载中以及加载失败图片
    public static void loadImageViewLoding(Context context, Object path, ImageView imageView, int lodingImage, int errorImageView) {
        Glide.with(context.getApplicationContext()).load(path).placeholder(lodingImage).error(errorImageView).into(imageView);
    }

    //设置加载中以及加载失败图片并且指定大小
    public static void loadImageViewLodingSize(Context context, Object path, int width, int height, ImageView imageView, int lodingImage, int errorImageView) {
        Glide.with(context.getApplicationContext()).load(path).override(width, height).placeholder(lodingImage).error(errorImageView).into(imageView);
    }

    //设置跳过内存缓存
    public static void loadImageViewCache(Context context, Object path, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).skipMemoryCache(true).into(imageView);
    }

    //设置下载优先级
    public static void loadImageViewPriority(Context context, Object path, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).priority(Priority.NORMAL).into(imageView);
    }

    /**
     * 策略解说：
     * <p>
     * all:缓存源资源和转换后的资源
     * <p>
     * none:不作任何磁盘缓存
     * <p>
     * source:缓存源资源
     * <p>
     * result：缓存转换后的资源
     */

    //设置缓存策略
    public static void loadImageViewDiskCache(Context context, Object path, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
    }

    /**
     * api也提供了几个常用的动画：比如crossFade()
     */

    //设置加载动画
    public static void loadImageViewAnim(Context context, Object path, int anim, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).animate(anim).into(imageView);
    }

    /**
     * 会先加载缩略图
     */

    //设置缩略图支持
    public static void loadImageViewThumbnail(Context context, Object path, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).thumbnail(0.1f).into(imageView);
    }

    /**
     * api提供了比如：centerCrop()、fitCenter()等
     */

    //设置动态转换
    public static void loadImageViewCrop(Context context, Object path, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).centerCrop().into(imageView);
    }

    //设置动态GIF加载方式
    public static void loadImageViewDynamicGif(Context context, Object path, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).asGif().into(imageView);
    }

    //设置静态GIF加载方式
    public static void loadImageViewStaticGif(Context context, Object path, ImageView imageView) {
        Glide.with(context.getApplicationContext()).load(path).asBitmap().into(imageView);
    }

    //设置监听的用处 可以用于监控请求发生错误来源，以及图片来源 是内存还是磁盘

    //设置监听请求接口
    public static void loadImageViewListener(Context context, String path, ImageView imageView, RequestListener<String, GlideDrawable> requstlistener) {
        Glide.with(context.getApplicationContext()).load(path).listener(requstlistener).into(imageView);
    }

    //项目中有很多需要先下载图片然后再做一些合成的功能，比如项目中出现的图文混排

    //设置要加载的内容
    public static void loadImageViewContent(Context context, Object path, SimpleTarget<GlideDrawable> simpleTarget) {
        Glide.with(context.getApplicationContext()).load(path).centerCrop().into(simpleTarget);
    }

    //清理磁盘缓存
    public static void clearDiskCache(final Context context) {
        //理磁盘缓存 需要在子线程中执行
        ThreadPoolUtils.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Glide.get(context.getApplicationContext()).clearDiskCache();
            }
        });

    }

    //清理内存缓存
    public static void clearMemory(Context context) {
        //清理内存缓存  可以在UI主线程中进行
        Glide.get(context.getApplicationContext()).clearMemory();
    }

    /**
     * 清除图片磁盘缓存
     */
    public static void clearImageDiskCache(final Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(context.getApplicationContext()).clearDiskCache();
                    }
                }).start();
            } else {
                Glide.get(context.getApplicationContext()).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片内存缓存
     */
    public static void clearImageMemoryCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                Glide.get(context.getApplicationContext()).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定目录下的文件，这里用于缓存的删除
     *
     * @param filePath filePath
     * @param deleteThisPath deleteThisPath
     */
    private static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 清除图片所有缓存
     */
    public static void clearImageAllCache(Context context) {
        clearImageDiskCache(context);
        clearImageMemoryCache(context);
        String ImageExternalCatchDir = context.getExternalCacheDir()+ ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;
        LogUtil.i("clearImageAllCache:" + ImageExternalCatchDir);
        deleteFolderFile(ImageExternalCatchDir, true);
    }

}
